package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"video-mgmt-sys/model"
	"video-mgmt-sys/pkg"
)

func VideoListByLike(c *gin.Context) {
	var video []model.Video
	err := model.DB.Order("`like` desc").Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
func VideoListByCollect(c *gin.Context) {
	var video []model.Video
	err := model.DB.Order("`collect` desc").Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
func VideoList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var video []model.Video
	model.DB.Offset(offset).Limit(size).Find(&video)
	//model.DB.Offset(offset).Limit(size).Order("like").Find(&video)
	var total int64
	model.DB.Model(&model.Video{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  video,
		"total": total,
	})
	return
}
func CreateVideo(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	collect, _ := strconv.Atoi(c.PostForm("collect"))
	like, _ := strconv.Atoi(c.PostForm("like"))
	if title == "" || content == "" || collect == 0 || like == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "标题或内容不能为空",
		})
		return
	}
	data := model.Video{
		Title:   title,
		Content: content,
		Collect: collect,
		Like:    like,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}

func RegisterUser(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码不能为空",
		})
		return
	}
	user := model.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "注册成功",
		})
		return
	}
}

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user model.User
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}
